﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Util.Props;
using Linguist.Acoustic;
using Common.Logging;
using System.Diagnostics;

namespace Linguist.Acoustic
{
    /// <summary>
    /// Manages the set of units for a recognizer
    /// </summary>
    public class UnitManager: IConfigurable
    {
        /// <summary>
        /// The name for the silence unit
        /// </summary>
        public static String SILENCE_NAME = "SIL";
        private static int SILENCE_ID = 1;

        ///The silence unit
        public static Unit SILENCE = new Unit(SILENCE_NAME, true, SILENCE_ID);

        private Dictionary<String, Unit> ciMap = new Dictionary<String, Unit>()
        {
            {SILENCE_NAME, SILENCE}
        };

        private int nextID = SILENCE_ID + 1;
        

        public UnitManager() 
        {

        }

        public void newProperties(PropertySheet ps)
        {
            Trace.WriteLine("UnitManager.newProperties");
        }

        /// <summary>
        ///  Gets or creates a unit from the unit pool
        /// </summary>
        /// <param name="name">the name of the unit</param>
        /// <param name="filler"><code>true</code> if the unit is a filler unit</param>
        /// <param name="context"> the context for this unit</param>
        /// <returns>the unit</returns>
        public Unit getUnit(String name, Boolean filler, Context context)
        {
            Unit unit = null;
            if (ciMap != null && ciMap.ContainsKey(name))
                unit = ciMap[name];
            if (context == Context.EMPTY_CONTEXT)
            {
                if (unit == null)
                {
                    unit = new Unit(name, filler, nextID++);
                    ciMap.Add(name, unit);
                    //Trace.TraceInformation("CI Unit: " + unit);
                }
            }
            else
            {
                unit = new Unit(unit, filler, context);
            }
            return unit;
        }
        /// <summary>
        /// Gets or creates a unit from the unit pool
        /// </summary>
        /// <param name="name"></param>
        /// <param name="filler"></param>
        /// <returns></returns>
        public Unit getUnit(String name, Boolean filler)
        {
            return getUnit(name, filler, Context.EMPTY_CONTEXT);
        }
        /// <summary>
        /// Gets or creates a unit from the unit pool
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Unit getUnit(String name)
        {
            return getUnit(name, false, Context.EMPTY_CONTEXT);
        }
    }
}
